<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster" >
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>资产库管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">目录管理</span></el-breadcrumb-item>
                </el-breadcrumb>
            </el-header>
            <el-container class="pl20 pr20" style="display: flex">
                <el-card class="mr15 cardMinWidth autoHeight">
                    <div slot="header">
                        <span>资产库列表</span>
                    </div>
                    <!-- 滚动条 -->
                    <div class="mytree">
                        <el-tree :data="groupTreeData"
                                ref="groupTreeData"
                                :props="groupTreeDataProps"
                                :expand-on-click-node="false"
                                :default-expanded-keys="defaultExpandKeys"
                                @node-expand="handleNodeExpand" 
                                @node-collapse="handleNodeCollapse" 
                                :highlight-current="true"
                                node-key="id"
                                @node-click="clickNode">
                            <span slot-scope="{ node, data }">
    <!--                            <span v-if="data.id==''" class="labelstyleTree tx-Elps main-Clr-ft" :title="node.label" >{{ node.label }}</span>-->
                                <span  class="labelstyleTree tx-Elps" :title="node.label" >{{ node.label }}</span>
                                <span>
                                    <span v-if="data.children">
                                        <i title="添加" class="iconfont icon-tianjia ml2 mr2 main-Clr-ft" @click.stop="addNode(data,node)"></i>
                                        <i title="删除" class="iconfont icon-shanchu main-Clr-ft" v-if="data.children.length<1" @click.stop="() => deleteNode(node, data)"></i>
                                    </span>
                                    <span v-else>
                                        <i title="取消添加" class="iconfont icon-shanchu ml2 mr2 main-Clr-ft" @click.stop="cancel(node, data)"></i>
                                    </span>
                                </span>
                            </span>
                        </el-tree>
                    </div>
                </el-card>

                <el-card class="autoHeight cardWidth" v-show="showFlag" style="flex:1">
                    <div slot="header">
                        <span v-if="flage">
                            <span>新建</span>
                            <span class="main-Clr-ft ml2 mr2">{{patientRole.libraryName}}</span>
                            <span>的子目录</span>
                        </span>
                        <span v-else>
                            当前编辑
                            <span class="main-Clr-ft ml2" >{{comparFormValue.libraryName}}</span>
                        </span>
                    </div>
                    <el-form
                            :model="inpFormValue"
                            ref="inpFormValue"
                            :rules="formRules">

                        <el-form-item label="目录名称:" prop="libraryName" label-width="19%">
                            <el-input v-model.trim="inpFormValue.libraryName" placeholder="请输入目录名称" size="small" id="groupNameID" class="inputWidth" maxlength="225"></el-input>
                        </el-form-item>

                        <el-form-item label="上级目录:" label-width="19%">
                            {{inpFormValue.parentName}}
                        </el-form-item>

                        <el-form-item label="目录顺序:" prop="orderId" label-width="19%">
                            <el-input placeholder="请输入目录顺序" type="number" v-model.trim="inpFormValue.orderId" size="small" class="inputWidth"></el-input>
                        </el-form-item>

                        <el-form-item label="目录说明:" prop="description" label-width="19%" class="mb10">
                            <el-input placeholder="请输入目录说明" type="textarea" :autosize="{minRows: 2, maxRows: 4}" v-model.trim="inpFormValue.description" maxlength="50" class="inputWidth"></el-input>
                            <div class="textAlignRight clr-dk-sp5 countNumber">{{inpFormValue.description.length}}/50</div>
                        </el-form-item>

                        
                        <el-form-item label="创建人:" label-width="19%">
                            {{inpFormValue.createBy}}
                        </el-form-item>
                    
                        <el-form-item label="创建时间:" label-width="19%" >
                            {{inpFormValue.createDate}}    
                        </el-form-item>

                        <el-form-item label="更新人:" label-width="19%" v-if="inpFormValue.updateBy != null">
                             {{inpFormValue.updateBy}}    
                        </el-form-item>
        
                        <el-form-item label="更新时间:" label-width="19%" v-if="inpFormValue.updateDate != null">
                             {{inpFormValue.updateDate}}  
                        </el-form-item>
                        
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('inpFormValue')" size="small" class="submitButton">提交</el-button>
                            <el-button v-if="flage" class="bkmgColor" @click="resetForm('inpFormValue')" size="small">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import { Message } from 'element-ui';
    Vue.component(Message.name, Message);

    let asGroup = urlConfig.asGroupQueryAll;
    let deleteAsGroup = urlConfig.asGroupDeleteById;
    let insertAsGroup = urlConfig.asGroupInsert;
    let updateAsGroup = urlConfig.asGroupUpdate;
    export default {
        data(){
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入目录顺序'));
                } else {
                    if(!/^[0-9]+$/.test(value)) {
                        callback(new Error('目录顺序必须为数字'));
                    }
                    callback();
                }
            };
            return{
                compareFlag:true,                       //新旧值对比标识,true代表相同
                showFlag:false,
                selectFlag:true,
                flage:false,                            //标记是否添加
                groupTreeData : [{
                    id:-1,
                    libraryName:'目录根结点',
                    children:[]
                    }],
                groupTreeDataProps:{
                    children: 'children',
                    label: 'libraryName',
                },
                inpFormValue : {            //表单
                    "id":'',
                    "libraryName":"",
                    "parentId":'',
                    "parentName":"",
                    "orderId":'',
                    "description":"",
                    "createBy":'',
                    "createDate":'',
                    "updateBy":'',
                    "updateDate":'',
                    "path":'',
                    children:[]
                },
                comparFormValue : {},//比较用数据
                patientRole : {},//新添加角色的父角色
                formRules: {
                    libraryName: [
                        { required: true,message:'必填信息',trigger: 'blur' },        //required   是否必填
                        { max: 255, message: '最长255个字符', trigger: 'blur' }
                    ],
                    orderId:[
                        { required: true,validator: validatePass, trigger: 'blur'},
                        {  max: 3, message: '长度在3个字符以内', trigger: 'blur' }
                    ],

                },
                defaultExpandKeys:[-1]
            }
        },
       
        methods: {
            // 树节点展开
            handleNodeExpand(data) {
                debugger
                // 保存当前展开的节点
                this.defaultExpandKeys.push(data.id); // 在节点展开是添加到默认展开数组
            },
            //获取树的数据
            getTreeData(){
                debugger;
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'post',
                    url: asGroup,
                    baseURL:'/api',
                    data: {
                        method:''
                    }
                }).then(function(response){
                    if(response.data.code == 1) {
                        var newdata=response.data.data;
                        that.groupTreeData[0].children = that.getJsonTree(newdata,'-1');
                        for (let i = 0; i < that.groupTreeData[0].children.length; i++) {
                            that.groupTreeData[0].children[i].parentId = '0'
                        }
                    }else{
                        Message.error('获取资产库树失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取资产库树失败');
                    loading.close();
                });
            },

            getJsonTree(newdata,parentId){
                let that=this;
                var itemArr=[];
                for(var i=0;i<newdata.length;i++){
                    var node=newdata[i];
                    if(node.PARENT_ID == parentId ){
                        var newNode={id:node.ID,
                            libraryName:node.LIBRARY_NAME,
                            parentId:node.PARENT_ID,
                            orderid:node.ORDERID,
                            description:node.DESCRIPTION,
                            createBy:node.CREATE_BY,
                            createDate:node.CREATE_DATE,
                            updateBy:node.UPDATE_BY,
                            updateDate:node.UPDATE_DATE,
                            path:node.PATH,
                            children:that.getJsonTree(newdata,node.ID)};
                        itemArr.push(newNode);
                    }
                }
                itemArr.sort(that.up);
                return itemArr;
            },

            up(x,y){
                return x.orderid-y.orderid
            },

            //新旧值对比
            compareData(){
                let that=this;
                if(that.showFlag==false){
                    that.compareFlag = true;
                }
                else if(that.inpFormValue.libraryName !== that.comparFormValue.libraryName || that.inpFormValue.description !== that.comparFormValue.description){
                    that.compareFlag=false;
                }else{
                    that.compareFlag=true;
                }
            },

            //获取树节点数据
            getData(data){
                let that = this;
                this.$refs['inpFormValue'].clearValidate();

                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'post',
                    url: asGroup,
                    baseURL:'/api',
                    data: {
                        id: data.id,
                        parentId: data.parentId,
                        method:"byId"
                    }
                }).then(function(response){
                    if(response.data.code=1) {
                        debugger
                        that.inpFormValue= response.data.data[0];
                        that.showFlag = true;
                        //对比新旧值用
                        that.comparFormValue.id= response.data.data[0].id;
                        that.comparFormValue.libraryName= response.data.data[0].libraryName;
                        that.comparFormValue.description= response.data.data[0].description;
                        // if(response.data.data.weekFlag==1){
                        //     that.comparFormValue.weekFlag=true;
                        //     that.inpFormValue.weekFlag=true;
                        // }else{
                        //     that.comparFormValue.weekFlag=false;
                        //     that.inpFormValue.weekFlag=false;
                        // }
                    }else{
                        Message.error('获取组信息失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取小组失败');
                    loading.close();
                });
            },

            //点击树节点-->获取组信息
            clickNode(data,node){
                debugger
                if(data.id=='-1'){
                    //如果点击的是虚拟根节点 不做任何操作
                    return;
                }
                let that = this;
                that.compareData();

                if(that.flage){
                    Message.warning('请先完成本次添加')
                }else if(!that.compareFlag){
                    this.$confirm('是否取消当前操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getData(that.inpFormValue.id);
                        Message.info('操作已取消');
                        that.compareFlag=true;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    that.getData(data);
                }
            },

            //添加节点
            addData(data,node){
                debugger;
                let that=this;
                this.$refs['inpFormValue'].clearValidate();
                //创建人
                var username = JSON.parse(window.localStorage["loginData"])["username"];
                //创建时间
                var createDate = that.sysdate();
                //一级菜单目录路径是本身
                const newChild = { id: that.uuid(), libraryName: '新目录',parentId:data.id,path: '',parentName:data.libraryName,description:'',createBy:username,createDate:createDate};
                if (!data.children) {
                    this.$set(data, 'children', []);
                }
                data.children.push(newChild);
                that.inpFormValue=newChild;
                that.flage=true;
                that.patientRole=data;
                that.showFlag = true;

            },

            //点击'添加'按钮-->添加节点
            addNode(data,node){
                debugger
                let that = this;
                that.compareData();
                if(that.flage){
                    Message.warning('请先完成上次添加')
                }else if(!that.compareFlag){
                    this.$confirm('是否取消当前操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getData(that.comparFormValue.id);
                        Message.info('操作已取消');
                        that.compareFlag=true;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    this.$refs.groupTreeData.setCurrentKey(data.id);
                    that.addData(data,node);
                }
            },

            //取消添加
            cancel(node, data){
                let that=this;
                this.$confirm('是否取消当前操作?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const parent = node.parent;
                    const children = parent.data.children || parent.data;
                    const index = children.findIndex(d => d.id === data.id);
                    children.splice(index, 1);
                    that.flage=false;
                    that.showFlag=false;
                    Message.info('操作已取消');
                    // this.$refs.groupTreeData.setCurrentKey(data.id);
                    // that.getData(that.comparFormValue.id);
                    that.$refs['inpFormValue'].clearValidate();
                    that.getTreeData();
                }).catch(() => {
                    Message.info('请继续操作');
                });
            },

            //删除节点
            deleteData(data){
                debugger
                let that=this;
                this.$confirm('确定要删除    <span class="main-Clr-ft">'+ data.libraryName   +'</span>    吗？','温馨提示',{
                    dangerouslyUseHTMLString: true,
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type:'warning'
                }).then(() => {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    });
                    this.$http({
                        method: 'delete',
                        url: deleteAsGroup,
                        baseURL:'/api',
                        data:{
                            "id":data.id,
                        }
                    }).then(function(response){
                        debugger
                        if(response.data.code == 1) {
                            Message.success('删除成功');
                            that.showFlag=false;
                            that.getTreeData();
                        }else{
                            Message.error(response.data.message);
                        }
                        loading.close();
                    }).catch(function(err){
                        Message.error('删除失败');
                        console.log(err);
                        loading.close();
                    });
                }).catch(() => {
                    Message.info('已取消删除');
                });
            },

            //点击'删除'按钮-->删除节点
            deleteNode(node, data){
                debugger;
                let that = this;
                that.compareData();
                if(that.flage){
                    Message.warning('请先完成本次添加');
                }else if(!that.compareFlag){
                    this.$confirm('是否删除当前新增节点操作', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.$refs['inpFormValue'].clearValidate();
                        that.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        that.getTreeData();
                        Message.info('操作已取消');
                        that.compareFlag=true;
                        that.showFlag = false;
                    }).catch(() => {
                        this.$refs.groupTreeData.setCurrentKey(that.comparFormValue.id);
                        Message.info('请继续操作');
                    });
                }else{
                    this.$refs.groupTreeData.setCurrentKey(data.id);
                    that.deleteData(data);
                }
            },

            //添加和修改的提交
            submitForm(formName,node){
                let that=this;
                debugger;
                // var uuid = that.uuid();
                var method = (that.flage? "post":"put");
                if(that.flage) {
                    var url = insertAsGroup;
                }else{
                    var url = updateAsGroup;
                    //修改人
                    var username = JSON.parse(window.localStorage["loginData"])["username"];
                    //修改时间
                    var updateDate = that.sysdate();
                }
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        this.$http({
                            method: method,
                            url: url,
                            baseURL:'/api',
                            data:{
                                'id': that.inpFormValue.id,
                                'libraryName':that.inpFormValue.libraryName,
                                'parentId':that.inpFormValue.parentId,
                                'description':that.inpFormValue.description,
                                'orderId':that.inpFormValue.orderId,
                                'createBy':that.inpFormValue.createBy,
                                'createDate':that.inpFormValue.createDate,
                                'updateBy':username,
                                'updateDate':updateDate,
                                'path':that.inpFormValue.path
                                
                            }
                        }).then(function(response){
                            if(response.data.code==1) {
                                if(method=="post"){
                                    // that.inpFormValue.id = response.data.data.id;
                                }
                                that.comparFormValue.libraryName=that.inpFormValue.libraryName;
                                that.comparFormValue.description=that.inpFormValue.description;
                                Message.success('操作成功');
                                that.getTreeData();
                            }else{
                                if(method=="post") {
                                    Message.error(response.data.message);
                                }else{
                                    Message.error('操作失败');
                                }
                            }
                            that.flage=false;
                            loading.close();
                        }).catch(function(err){
                            Message.error('操作失败');
                            console.log(err);
                            that.flage=false;
                            that.getTreeData();
                            loading.close();
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            //重置
            resetForm(formName) {
                debugger
                this.$refs[formName].resetFields();
            },

            //日期
            sysdate() {
                //年
                var year = new Date().getFullYear();
                //月份是从0月开始获取的，所以要+1;
                var month = new Date().getMonth() +1;
                //日
                var day = new Date().getDate();
                return year + '-' + month + '-' + day
            },
            //uuid
            uuid() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";
                var uuid = s.join("");
                return uuid;
            },

        },
        mounted(){
            let that = this;
            that.getTreeData();

        },
        updated(){
            let that=this;
            if(this.selectFlag){
                //1页面加载完成左侧树默认选中
                // this.$refs.groupTreeData.setCurrentKey(that.defaultId);
                this.selectFlag=false;
            }

        }
    }
</script>

<style scoped>
.mytree >>> .el-tree {
    height: 450px;
    overflow-y: auto;
    /* border-right: solid 1px #ddd; */
}
.mytree >>> .el-tree::-webkit-scrollbar {
    width: 10px;
}
div::-webkit-scrollbar{
  width:10px;
  height:10px;
  /**/
}
div::-webkit-scrollbar-track{
  background: rgb(239, 239, 239);
  border-radius:2px;
}
div::-webkit-scrollbar-thumb{
  background: #bfbfbf;
  border-radius:10px;
}
div::-webkit-scrollbar-thumb:hover{
  background: #333;
}
div::-webkit-scrollbar-corner{
  background: #179a16;
}
    .inputWidth{
        width: 77%;
    }

    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    /*计数*/
    .countNumber{
        margin-right: 23%;
    }

    .submitButton{
        margin-left: 19%;
    }

    /*.roleCardHight {*/
    /*height: 611px;*/
    /*}*/

    .cardMinWidth{
        min-width: 275px;
    }

    .cardWidth{
        width: 100%;
    }
</style>